var express = require('express');
var router = express.Router();
var userModel = require('../../../database/model/userModel')
var bcrypt = require('bcryptjs')
var salt = bcrypt.genSaltSync(10);   //密码加密 盐
var jwt = require('jsonwebtoken') //服务器签发token的模块
var secret = 'alsdkjfalsdufioj4654asdfasdf'  //服务器私钥

router.post('/register',(req,res)=>{  //用户注册
  let {username,password,Email} = req.body
  userModel.find({username:username}).then(result=>{
    if(result.length!=0){  //判断账号是否已被注册
      res.send({
        code:0,
        msg:'账号已被占用'
      })
      return
    }
    let hash = bcrypt.hashSync(password,salt)  //密码加密
    new userModel({  //向用户表新增用户
      username:username,
      password: hash,
      Email:Email
    }).save().then(data=>{
      res.send({
        code:200,
        msg:'注册成功'
      })
    })
  })
})

router.post('/login',(req,res)=>{ //用户登录
  let {username,password} = req.body
  userModel.find({username}).then(result=>{
    if(result.length==0){  //判断账号是否存在
      res.send({
        code:0,
        msg:'账号不存在，请注册'
      })
      return
    }
    let bool = bcrypt.compareSync(password,result[0].password) //密码比对
    if(!bool){  //密码错误的逻辑
      res.send({
        code:0,
        msg:'密码错误'
      })
      return
    }
   let {avator,_id,username}=result[0]
   let userInfo=JSON.parse(JSON.stringify(result[0]))
    let token = jwt.sign({
      time:Date.now(),  //签发时间
      limit:1000*60*60, //token有效时长 10min
      ...userInfo
    },secret)  //生成token
    res.status(200).send({  //登录成功并下发用户信息
      code:200,
      msg:'登录成功',
      data:{avator,_id,username,token}
    })
  })
})
module.exports = router;
